<template>
  <div class="partner-link-manage">
    <el-container>
      <el-main>
        <div class="page-header">
          <h1>友链管理</h1>
          <el-button type="primary" @click="openAdd">新增友链</el-button>
        </div>

        <el-card>
          <div class="toolbar">
            <el-input
              v-model="keyword"
              placeholder="搜索名称/URL"
              style="max-width: 260px"
              clearable
            />
            <el-button type="primary" @click="loadList">搜索</el-button>
            <el-button :disabled="!selected.length" @click="batchDelete">批量删除</el-button>
          </div>
          <el-table :data="list" v-loading="loading" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column label="名称" prop="linkName" />
            <el-table-column label="Logo" width="120">
              <template #default="{ row }">
                <img
                  :src="row.logoUrl"
                  alt=""
                  style="width: 80px; height: 40px; object-fit: cover"
                />
              </template>
            </el-table-column>
            <el-table-column label="URL" prop="linkUrl" />
            <el-table-column label="排序" prop="sortOrder" width="90" />
            <el-table-column label="操作" width="180">
              <template #default="{ row }">
                <el-button size="small" @click="openEdit(row)">编辑</el-button>
                <el-button size="small" type="danger" @click="handleDelete(row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pager">
            <el-pagination
              background
              layout="prev, pager, next, jumper"
              :page-size="pageSize"
              :current-page="page"
              :total="total"
              @current-change="handlePageChange"
            />
          </div>
        </el-card>
      </el-main>
    </el-container>

    <el-dialog
      :title="editing ? '编辑友链' : '新增友链'"
      :model-value="dialogVisible"
      width="600px"
      @close="closeDialog"
    >
      <el-form :model="form" label-width="90px">
        <el-form-item label="名称">
          <el-input v-model="form.linkName" />
        </el-form-item>
        <el-form-item label="Logo URL">
          <el-input v-model="form.logoUrl" />
        </el-form-item>
        <el-form-item label="链接URL">
          <el-input v-model="form.linkUrl" />
        </el-form-item>
        <el-form-item label="排序值">
          <el-input v-model.number="form.sortOrder" type="number" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { adminService } from '@/api'

type Link = {
  id?: number
  linkName: string
  linkUrl?: string
  logoUrl?: string
  sortOrder?: number
}

const loading = ref(false)
const list = ref<Link[]>([])
const selected = ref<Link[]>([])
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
const keyword = ref('')

const dialogVisible = ref(false)
const editing = ref(false)
const editingId = ref<number | null>(null)
const form = ref<Link>({ linkName: '', linkUrl: '', logoUrl: '', sortOrder: 1 })

const loadList = async () => {
  loading.value = true
  try {
    const res = await adminService.getPartnerLinksList(
      page.value,
      pageSize.value,
      keyword.value || undefined,
    )
    const data: any = res.data?.data
    const pageInfo = data || {}
    list.value = pageInfo.list || pageInfo.data?.list || []
    total.value = pageInfo.total || pageInfo.data?.total || 0
  } finally {
    loading.value = false
  }
}

const handlePageChange = (p: number) => {
  page.value = p
  loadList()
}

const openAdd = () => {
  editing.value = false
  editingId.value = null
  form.value = { linkName: '', linkUrl: '', logoUrl: '', sortOrder: 1 }
  dialogVisible.value = true
}

const openEdit = (row: Link) => {
  editing.value = true
  editingId.value = row.id || null
  form.value = { ...row }
  dialogVisible.value = true
}

const closeDialog = () => {
  dialogVisible.value = false
}

const submit = async () => {
  if (editing.value && editingId.value) {
    await adminService.updatePartnerLink(editingId.value, form.value as any)
  } else {
    await adminService.addPartnerLink(form.value as any)
  }
  dialogVisible.value = false
  loadList()
}

const handleDelete = async (id?: number) => {
  if (!id) return
  await adminService.deletePartnerLink(id)
  loadList()
}

const handleSelectionChange = (rows: Link[]) => {
  selected.value = rows
}

const batchDelete = async () => {
  if (!selected.value.length) return
  const ids = selected.value.map((i) => i.id).filter(Boolean) as number[]
  if (!ids.length) return
  try {
    await adminService.batchDeletePartnerLinks(ids)
  } catch {
    await Promise.all(ids.map((id) => adminService.deletePartnerLink(id)))
  }
  selected.value = []
  await loadList()
}

onMounted(() => {
  loadList()
})
</script>

<style scoped>
.partner-link-manage {
  padding: 20px;
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}
.toolbar {
  display: flex;
  gap: 10px;
  margin-bottom: 12px;
}
.pager {
  display: flex;
  justify-content: flex-end;
  margin-top: 12px;
}
</style>
